package com.brayan.webapp.service.general.i18n;

import javax.ejb.Stateless;
import javax.inject.Inject;

import org.apache.log4j.Logger;

import com.brayan.webapp.model.general.i18n.Locale;
import com.brayan.webapp.model.general.i18n.Text;
import com.brayan.webapp.model.general.i18n.Translation;
import com.brayan.webapp.repository.general.i18n.LocaleRepository;
import com.brayan.webapp.repository.general.i18n.TextRepository;
import com.brayan.webapp.repository.general.i18n.TranslationRepository;

/**
 * Responsible for the i18n management. Is Stateful!
 * 
 * @author Brayan
 * 
 */
@Stateless
public class I18NBean {

	@Inject
	transient private Logger LOGGER;

	@Inject
	TextRepository textRepo;
	@Inject
	TranslationRepository transRepo;
	@Inject
	LocaleRepository localeRepo;

	/**
	 * Translates and adds tokens to database if they are missing.
	 * 
	 * @param token
	 * @param locale
	 * @return
	 */
	public String getTrans(String token, Locale locale) {
		if (locale != null) {
			Translation trans = transRepo.getTranslationByTokenAndLocaleId(token, locale);
			if (trans == null || trans.getTranslation().isEmpty()) {
				createNewToken(token);
				return wrapToken(token);
			} else
				return trans.getTranslation();
		} else {
			Text text = textRepo.getTextUnitByToken(token);
			// Check if Text token exists. If not, create it.
			if (text != null)
				return text.getDefaultText();
			else {
				createNewToken(token);
				return wrapToken(token);
			}
		}
	}

	private void createNewToken(String token) {
		Text text = textRepo.getTextUnitByToken(token);
		if (text == null) {
			Text newText = new Text();
			newText.setToken(token);
			newText.setDefaultText(wrapToken(token));
			textRepo.saveTextToken(newText);
			LOGGER.info("Created an in-existing token (" + token + ").");
		}
	}

	/**
	 * Wraps token name into non-existing translation.
	 * 
	 * @param token
	 * @return
	 */
	private String wrapToken(String token) {
		String newToken = "#" + token;

		return newToken;
	}

}
